package com.winner.crmsoftware.customers;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.winner.crmsoftware.location.GPSTracker;
import com.winner.crmsoftware.main.R;
import com.winner.crmsoftware.ultil.LocationObject;
import com.winner.srmsoftware.json.ServiceHandler;

public class CustomerOnMapActivity extends Activity {

	// Google Map
	private GoogleMap googleMap;

	private ProgressDialog pDialog;
	ArrayList<LocationObject> dataArrayList = new ArrayList<LocationObject>();
	private static String url = "http://103.28.37.16:8080/crm_software/get_all_customers.php";
	private static final String TAG_CUSTOMER = "customers";
	private static final String TAG_LATITUDE = "latitude";
	private static final String TAG_LONGTITUDE = "longtitude";
	private static final String TAG_NAME = "last_name";
	private static final String TAG_ADDRESS = "address";
	public GPSTracker gps;
	JSONArray customerJsonArray = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.customer_on_map);

		gps = new GPSTracker(CustomerOnMapActivity.this);
		if (!gps.canGetLocation()) {
			gps.showSettingsAlert();
		}

		new GetContacts().execute();

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    // Inflate the menu items for use in the action bar
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.custom_map_menu, menu);
	    return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onResume() {
		super.onResume();
		initilizeMap();
	}

	@SuppressLint("NewApi")
	private void initilizeMap() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.customer_on_map)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getApplicationContext(),
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/**
	 * Async task class to get json by making HTTP call
	 * */
	private class GetContacts extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			pDialog = new ProgressDialog(CustomerOnMapActivity.this);
			pDialog.setMessage("Please wait...");
			pDialog.setCancelable(false);
			pDialog.show();

		}


		@SuppressLint("DefaultLocale")
		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);

					// Getting JSON Array node
					customerJsonArray = jsonObj.getJSONArray(TAG_CUSTOMER);

					Log.e("Json Length", customerJsonArray.length() + "");
					// looping through All Contacts
					for (int i = 0; i < customerJsonArray.length(); i++) {
						JSONObject c = customerJsonArray.getJSONObject(i);

						String latitude = c.getString(TAG_LATITUDE);
						String longtitude = c.getString(TAG_LONGTITUDE);
						String name = c.getString(TAG_NAME);
						String address = c.getString(TAG_ADDRESS);

						String title = name + " Address: " + address;

						LocationObject locationObject = new LocationObject(
								Double.valueOf(latitude),
								Double.valueOf(longtitude), title);

						// Phone node is JSON Object

						// adding contact to contact list
						dataArrayList.add(locationObject);
						Log.e("Data SIze", dataArrayList.size() + "");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			Log.e("Add custom: ", "" + dataArrayList.size());
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */

			try {
				// Loading map
				initilizeMap();

				// Changing map type
				googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

				// Showing / hiding your current location
				googleMap.setMyLocationEnabled(true);

				// Enable / Disable zooming controls
				googleMap.getUiSettings().setZoomControlsEnabled(false);

				// Enable / Disable my location button
				googleMap.getUiSettings().setMyLocationButtonEnabled(true);

				// Enable / Disable Compass icon
				googleMap.getUiSettings().setCompassEnabled(true);

				// Enable / Disable Rotate gesture
				googleMap.getUiSettings().setRotateGesturesEnabled(true);

				// Enable / Disable zooming functionality
				googleMap.getUiSettings().setZoomGesturesEnabled(true);

				// lets place some 10 random markers
				for (int i = 0; i < dataArrayList.size(); i++) {
					// random latitude and logitude

					Log.e("Makeer", "" + dataArrayList.size());

					// Adding a marker
					MarkerOptions marker = new MarkerOptions().position(
							new LatLng(dataArrayList.get(i).getLatitude(),
									dataArrayList.get(i).getLongitude()))
							.title(dataArrayList.get(i).getTitle());

					marker.icon(BitmapDescriptorFactory
							.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

					googleMap.addMarker(marker);

					// Move the camera to last position with a zoom level
					if (i == (dataArrayList.size() - 1)) {
						CameraPosition cameraPosition = new CameraPosition.Builder()
								.target(new LatLng(dataArrayList.get(i)
										.getLatitude(), dataArrayList.get(i)
										.getLongitude())).zoom(15).build();

						googleMap.animateCamera(CameraUpdateFactory
								.newCameraPosition(cameraPosition));
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
